#include "superdatasetgeneratordialog.h"
#include "ui_superdatasetgeneratordialog.h"

SuperDatasetGeneratorDialog::SuperDatasetGeneratorDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::SuperDatasetGeneratorDialog)
{
    ui->setupUi(this);

    connect(ui->plain_hrefs, &QPlainTextEdit::textChanged, this, &SuperDatasetGeneratorDialog::plain_hrefs_textChanged);
    connect(ui->plain_texts, &QPlainTextEdit::textChanged, this, &SuperDatasetGeneratorDialog::plain_texts_textChanged);
}

SuperDatasetGeneratorDialog::~SuperDatasetGeneratorDialog()
{
    delete ui;
}


void SuperDatasetGeneratorDialog::updateOutput()
{
    auto hrefsdata = ui->plain_hrefs->toPlainText();
    auto textsdata = ui->plain_texts->toPlainText();
    auto outputsdata = ui->plain_outputs->toPlainText();

    auto hrefs = hrefsdata.split("\n",Qt::SkipEmptyParts);
    auto texts = textsdata.split("\n",Qt::SkipEmptyParts);

    ui->btn_yep->setEnabled(hrefs.count() == texts.count());
    ui->plain_outputs->clear();

    if (ui->btn_yep->isEnabled()) {
        for (int i = 0; i < hrefs.count(); ++i) {
            auto href = hrefs[i];
            auto text = texts[i];

            auto output = QString("<a href=\"%1\">%2</a>").arg(href).arg(text);
            ui->plain_outputs->appendPlainText(output);
        }
    }
}

QString SuperDatasetGeneratorDialog::outputs()
{
    auto outputsdata = ui->plain_outputs->toPlainText();
    return outputsdata;
}

void SuperDatasetGeneratorDialog::setOutputs(const QString &output)
{
    disconnect(ui->plain_hrefs, &QPlainTextEdit::textChanged, this, &SuperDatasetGeneratorDialog::plain_hrefs_textChanged);
    disconnect(ui->plain_texts, &QPlainTextEdit::textChanged, this, &SuperDatasetGeneratorDialog::plain_texts_textChanged);

    foreach (auto line, output.split("\n", Qt::SkipEmptyParts)) {
        auto title = line.mid(line.indexOf(">") + 1);
        title = title.mid(0, title.indexOf("</a>"));

        auto href = line.mid(line.indexOf("href=") + 6);
        href = href.mid(0, href.indexOf(">") - 1);

        ui->plain_hrefs->appendPlainText(href);
        ui->plain_texts->appendPlainText(title);
    }

    updateOutput();
    connect(ui->plain_hrefs, &QPlainTextEdit::textChanged, this, &SuperDatasetGeneratorDialog::plain_hrefs_textChanged);
    connect(ui->plain_texts, &QPlainTextEdit::textChanged, this, &SuperDatasetGeneratorDialog::plain_texts_textChanged);
}

void SuperDatasetGeneratorDialog::plain_hrefs_textChanged()
{
    updateOutput();
}

void SuperDatasetGeneratorDialog::plain_texts_textChanged()
{
    updateOutput();
}

void SuperDatasetGeneratorDialog::on_btn_yep_clicked()
{
    accept();
}
